package com.ian.config;

import com.ian.annotation.WithMockCustomUser;
import com.ian.entity.CustomUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.test.context.support.WithSecurityContextFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * 创建 SecurityContext 实例的工厂
 * 工厂方法模式（定义了一个创建对象的接口，但是让子类决定实例化哪个类。工厂方法推迟了一个类的实例化动作到子类）
 * @author Witt
 * @version 1.0.0
 * @date 2022/5/14
 */
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
    @Override
    public SecurityContext createSecurityContext(WithMockCustomUser customUser) {

        SecurityContext context = SecurityContextHolder.createEmptyContext();
        // create a Custom UserDetails instance
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_user"));
        UserDetails principal = new CustomUserDetails(customUser.name(), customUser.username(), "123", authorities);

        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(principal, "password1", principal.getAuthorities());
        context.setAuthentication(authentication);
        return context;
    }
}
